package com.magic.service.mobile;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.magic.util.DateUtil;


/**
 * ClassName: SmsService <br/>
 * Function: 短信服务. <br/>
 * date: 2018年10月18日 下午6:00:20 <br/>
 * 
 * @author lishuai8
 * @version
 * @since JDK 1.8
 */
@Service("smsService")
public class SmsService {

	private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

	@Value("${sms.api}")
	private String smsServicesApi;

	@Value("${sms.uid}")
	private String userId;

	@Value("${sms.password}")
	private String smsPassword;

	public String sendSms(String mobile, String code) {
		// 短信发送状态
		String state = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		try {

			URIBuilder uri = new URIBuilder(smsServicesApi);
			String tm = DateUtil.localTimeBySms();
			uri.addParameter("uid", userId);
			uri.addParameter("pw", DigestUtils.md5Hex(smsPassword + tm));
			uri.addParameter("mb", mobile);
			uri.addParameter("ms", "【24K少儿英语】验证码：" + code + "感谢您使用24K天天少儿英语");
			uri.addParameter("tm", tm);
			HttpGet httpGet = new HttpGet(uri.build());
			httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			// 将远程返回的信息进行处理 0：表示短信发送成功
			state = EntityUtils.toString(entity);
			if (state.indexOf(",") != -1) {
				state = state.split(",")[0];
				logger.info("信息发送成功,state:{}", state);
			} else {
				logger.info("信息发送失败,state:{}", state);
			}
		} catch (IOException e) {
			logger.error("sendSms() IO exception: {}", e);
		} catch (URISyntaxException e) {
			logger.error("sendSms() URISyntaxException: {}", e);
		} finally {
			if (entity != null) {
				try {
					EntityUtils.consume(entity);
				} catch (IOException e) {
					logger.error("sendSms() IOException:", e);
				}
			}
		}
		return state;
	}
}
